<template>
	<view class="content">

		<view class="top">
			<image src="@/static/activity/centuryLaborUnion/AITop.jpg" mode=""></image>
		</view>

		<view class="below">

			<view style="height: 145rpx;" @click="downloadImg"></view>

			<view class="function">

				<view style="height: 5rpx;"></view>

				<view class="opaque">
					<view class="text">上传照片:</view>
					<view class="jia" @click="jia" v-if="images.length < 3">
						<image src="@/static/activity/centuryLaborUnion/jia.png" mode=""></image>
					</view>
					<view class="opaque_for" v-for="(item, idx) in images">
						<view class="rahmen">
							<image :src="item" mode=""></image>
							<view class="shanchu" @click="deleteImages(idx)">删除</view>
						</view>
					</view>
				</view>

				<view class="opaque">
					<view class="text">选择相框:</view>
					<view class="opaque_for" v-for="(item, idx) in frames" @click="select_frames(item.id)">
						<view class="rahmen" :class="frames_index == item.id ? 'rahmen_yes' : 'rahmen'">
							<image :src="localIp + item.url" mode=""></image>
						</view>
					</view>
				</view>

				<view class="opaque">
					<view class="text">选择背景图:</view>
					<view class="opaque_for" v-for="(item, idx) in backgrounds" @click="select_backgrounds(item.id)">
						<view class="rahmen" :class="backgrounds_index == item.id ? 'rahmen_yes' : 'rahmen'">
							<image :src="localIp + item.url" mode=""></image>
						</view>
					</view>
				</view>

				<view class="AIsc" @click="create">
					<image src="@/static/activity/centuryLaborUnion/AIsc.png" mode=""></image>
				</view>

			</view>

			<gui-popup ref="gui_createdPicture" :canCloseByShade="false">
				<view class="created_picture">
					<view class="created_picture_img">
						<img :src="createdPicture" alt="" />
					</view>
					<view class="operation">
						<view class="download_img" @click="downloadImg">保存图片</view>
						<view class="save_img" @click="againImg">重新上传</view>
					</view>
				</view>
			</gui-popup>

		</view>

	</view>
</template>
<script>
	export default {
		data() {
			return {
				localIp: 'https://photom.boyaltd.cn',
				uploadedImage: null,
				images: [],
				frames: [],
				frames_index: 0,
				backgrounds: [],
				backgrounds_index: 0,
				createdPicture: '',
			}
		},
		onLoad(opt) {
			this.show_loading();
			this.get_frames();
			this.get_backgrounds();
		},
		methods: {
			get_server() {
				const os = require('os');
				const networkInterfaces = os.networkInterfaces();
				let localIp = '171.111.195.66';
				for (let interfaceName in networkInterfaces) {
					networkInterfaces[interfaceName].forEach((interfaceDetails) => {
						if (interfaceDetails.family === 'IPv4' && !interfaceDetails.internal) {
							localIp = interfaceDetails.address;
						}
					});
				}
				// this.localIp = `https://photom.boyaltd.cn`
				this.localIp = `http://${localIp}:8001`
				console.log('服务器: ', this.localIp);
				this.get_frames();
				this.get_backgrounds();
			},
			// 随机
			get_three(arr) {
				let count = 3
				let clonedArr = [...arr];
				let randomItems = [];
				// 随机取 count 个对象
				for (let i = 0; i < count; i++) {
					// 如果数组为空，则退出
					if (clonedArr.length === 0) break;
					// 生成一个随机索引
					let randomIndex = Math.floor(Math.random() * clonedArr.length);
					// 从数组中移除该随机对象，并加入结果数组
					randomItems.push(clonedArr.splice(randomIndex, 1)[0]);
				}
				return randomItems;
			},
			// 获取相框列表
			get_frames() {
				let self = this
				self.$boya.Request({
					url: '/public/frames',
					method: "GET",
				}, function(res) {
					console.log('相框列表：', res);
					if (res.code == 200) {
						if (res.data.length > 3) {
							self.frames = self.get_three(res.data)
						} else {
							self.frames = res.data
						}
					} else {
						uni.showToast({
							title: '相框获取失败',
							duration: 2000,
							icon: 'error'
						});
					}
					console.log('self.frames: ', self.frames);
					self.hide_loading();
				}, false)
			},
			// 获取背景列表
			get_backgrounds() {
				let self = this
				self.$boya.Request({
					url: '/public/bg',
					method: "GET",
				}, function(res) {
					console.log('背景图列表：', res);
					if (res.code == 200) {
						if (res.data.length > 3) {
							self.backgrounds = self.get_three(res.data)
						} else {
							self.backgrounds = res.data
						}
					} else {
						uni.showToast({
							title: '背景获取失败',
							duration: 2000,
							icon: 'error'
						});
					}
					console.log('self.backgrounds: ', self.backgrounds);
					self.hide_loading();
				}, false)
			},
			// 添加图片
			jia() {
				if (this.images.length >= 3) {
					uni.showToast({
						title: '最多只可上传 3 张图片',
						duration: 2000,
						icon: 'none'
					});
				} else {
					uni.chooseImage({
						count: 3,
						sizeType: ['compressed'],
						sourceType: ['album', 'camera'],
						success: (res) => {
							this.images.push(res.tempFilePaths[0]);
							console.log('images: ', this.images);
						},
						fail: (err) => {
							uni.showToast({
								title: '选择图片失败',
								icon: 'none'
							});
						}
					});
				}
			},
			deleteImages(idx) {
				this.images.splice(idx, 1);
			},
			select_frames(id) {
				this.frames_index = id
			},
			select_backgrounds(id) {
				this.backgrounds_index = id
			},
			create() {
				let self = this
				if (self.images.length <= 0) {
					uni.showToast({
						title: '请最少上传一张照片',
						icon: 'none'
					});
				} else if (self.frames_index == 0) {
					uni.showToast({
						title: '请选择相框',
						icon: 'none'
					});
				} else if (self.backgrounds_index == 0) {
					uni.showToast({
						title: '请选择背景图',
						icon: 'none'
					});
				} else {
					uni.showLoading({
						title: '生成中...'
					});

					let shuju = self.images.map((image, index) => ({
						uri: image, // 本地文件路径
						name: 'user_images',
						type: 'image/jpeg' // 文件类型
					}));
					console.log('shuju: ', shuju);

					let data = {
						user_images: shuju,
						frame_id: self.frames_index,
						background_id: self.backgrounds_index
					}
					self.$boya.Request({
						url: '/public/process',
						data: data,
					}, function(res) {
						console.log('合成：', res);
						self.hide_loading();
					}, false)

					// 使用uni.uploadFile上传
					// uni.uploadFile({
					// 	// url: 'https://jf.lgwisdomunion.cn/api/public/process',
					// 	url: self.localIp + '/process/',
					// 	files: shuju,
					// 	formData: {
					// 		frame_id: self.frames_index,
					// 		background_id: self.backgrounds_index
					// 	},
					// 	success: (uploadFileRes) => {
					// 		console.log('res:', uploadFileRes);
					// 		try {
					// 			console.log('服务器返回:', uploadFileRes.data);
					// 			// 解析JSON响应
					// 			const response = JSON.parse(uploadFileRes.data);
					// 			if (response.detail) {
					// 				throw new Error(response.detail);
					// 			}
					// 			if (response.image) {
					// 				// 添加base64前缀
					// 				self.createdPicture = 'data:image/png;base64,' + response.image;
					// 				self.ceshixiazai = self.createdPicture
					// 				// console.log('处理后的图片数据:', self.createdPicture);
					// 				// 显示图片
					// 				self.$refs.gui_createdPicture.open();
					// 			} else {
					// 				throw new Error('未获取到图片数据');
					// 			}
					// 		} catch (error) {
					// 			console.error('处理图片失败:', error);
					// 			uni.showToast({
					// 				title: error.message || '图片处理失败',
					// 				duration: 2000,
					// 				icon: 'error'
					// 			});
					// 		} finally {
					// 			uni.hideLoading();
					// 		}
					// 	},
					// 	fail: (error) => {
					// 		console.error('上传失败:', error);
					// 		uni.showToast({
					// 			title: '上传失败，请重试',
					// 			duration: 2000,
					// 			icon: 'error'
					// 		});
					// 		uni.hideLoading();
					// 	}
					// });
				}
			},
			// 下载图片
			downloadImg() {
				console.log('保存图片');
				if (!this.ceshixiazai) {
					uni.showToast({
						title: '无图片',
						icon: 'error',
					});
					return
				};

				uni.showLoading({
					title: '保存中...'
				});

				// 将base64转换为临时文件
				const fs = uni.getFileSystemManager();
				const tempFilePath = `${uni.env.USER_DATA_PATH}/${new Date().getTime()}.png`;

				// 移除base64前缀
				const base64Data = this.ceshixiazai.replace(/^data:image\/\w+;base64,/, '');

				fs.writeFile({
					filePath: tempFilePath,
					data: base64Data,
					encoding: 'base64',
					success: () => {
						uni.saveImageToPhotosAlbum({
							filePath: tempFilePath,
							success: () => {
								uni.showToast({
									title: '保存成功',
									icon: 'success'
								});
							},
							fail: () => {
								uni.showToast({
									title: '保存失败',
									icon: 'none'
								});
							},
							complete: () => {
								uni.hideLoading();
							}
						});
					},
					fail: () => {
						uni.hideLoading();
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						});
					}
				});
			},
			// 重新上传
			againImg() {
				this.images = []
				this.frames_index = 0
				this.backgrounds_index = 0
				this.$refs.gui_createdPicture.close();
			},
			show_loading() {
				uni.showLoading({
					title: '加载中...'
				});
			},
			hide_loading() {
				uni.hideLoading();
			},
		}
	}
</script>

<style>
	.top {
		width: 100vw;
		height: 30vh;
	}

	.top>image {
		width: 100%;
		height: 100%;
	}

	.below {
		position: relative;
		z-index: 9;
		width: 100vw;
		height: 73vh;
		margin-top: -40rpx;
		background: url('../../../static/activity/centuryLaborUnion/AIdi.png') 100% 100% / 100% 100%;
	}

	.function {
		width: 90%;
		margin: 0 auto;
		min-height: 900rpx;
		border-radius: 20rpx;
		background-color: rgba(255, 255, 255, 0.6);
	}

	.opaque {
		width: 89%;
		margin: 0 auto;
		margin-top: 38rpx;
		height: 200rpx;
		border-radius: 20rpx;
		background-color: white;
		display: flex;
		align-items: center;
	}

	.text {
		margin: 0 20rpx;
	}

	.jia {
		width: 120rpx;
		height: 120rpx;
	}

	.jia>image {
		width: 100%;
		height: 100%;
	}

	.rahmen_yes {
		border: 6rpx solid rgba(211, 11, 8, 0.5);
		box-shadow: 6rpx 6rpx 15rpx #FFD49B;
		border-radius: 20rpx;
	}

	.rahmen {
		width: 120rpx;
		height: 120rpx;
		margin: 0 10rpx;
	}

	.rahmen>image {
		width: 100%;
		height: 100%;
		border-radius: 15rpx;
	}

	.shanchu {
		font-size: 28rpx;
		text-align: center;
		margin-top: -5rpx;
	}

	.AIsc {
		width: 50%;
		margin: 0 auto;
		height: 100rpx;
		margin-top: 45rpx;
	}

	.AIsc>image {
		width: 100%;
		height: 100%;
	}

	.created_picture {
		width: 100%;
		height: 90%;
		border-radius: 15rpx;
		background-color: white;
	}

	.created_picture_img {
		width: 100%;
		height: 88%;
	}

	.created_picture_img>img {
		width: 100%;
		height: 100%;
		border-top-left-radius: 15rpx;
		border-top-right-radius: 15rpx;
	}

	.operation {
		color: white;
		display: flex;
		align-items: center;
		justify-content: space-evenly;
		margin-top: 25rpx;
	}

	.operation>view {
		padding: 15rpx 25rpx;
		border-radius: 15rpx;
	}

	.download_img {
		background-color: #FF9800;
	}

	.save_img {
		color: black;
		background-color: #FFD49B;
	}
</style>